#include "serialportudprx.h"

#include <iostream>
// UDP报文接收类
SerialportUdprx::SerialportUdprx(QObject *parent)
{
    Q_UNUSED(parent);
    m_udpSocket = new QUdpSocket();
    // 获取系统参数
    PSysparamInfo sys_info;
    SERIALPORTCONFIG_INSTANCE->getSysParamInfo(sys_info);
    quint16 dataValue = 0;
    bool isOk;
    QString post = QString::number(sys_info.sudp_port);
    dataValue = post.toUShort(&isOk);
    init_port(dataValue);
    connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(readDatagrams()), Qt::DirectConnection );
}

SerialportUdprx::~SerialportUdprx() {
    m_udpSocket->close();
    m_udpSocket->deleteLater();
}

void SerialportUdprx::init_port(/*QString host , */quint16 port) {
    m_port = port;
    m_udpSocket->bind(QHostAddress::Any, m_port);
}

// 数据接收
void SerialportUdprx::readDatagrams() {
    QHostAddress client_address;
    m_data.clear();
    m_data.resize(m_udpSocket->pendingDatagramSize());

    m_udpSocket->readDatagram(m_data.data(), m_data.size(), &client_address );

    g_rcvDataQueue.enqueue(m_data);
}
